<script setup lang="ts">
import { useColumns } from "./columns";
import { Plus } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import InvoiceInfoForm from "./InvoiceInfoForm.vue";
import {
  ApplyInvoiceType,
  getInvoiceList,
  applyInvoice,
  updateInvoice,
  getInvoiceDetail,
  ApplyInvoiceResult
} from "@/api/invoice";
import { getExhibitorId } from "@/utils/getExhibitorId";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "invoiceInfo"
});

onMounted(() => {
  getInvoiceListData();
});

const invoiceList = ref([]);
const loading = ref(false);

// 分页信息
const pagination = ref({
  total: 0,
  page: 1,
  limit: 10
});

// 获取发票列表
const getInvoiceListData = async (page = 1, limit = 10) => {
  try {
    loading.value = true;
    const exhibitor_id = getExhibitorId();
    const result = await getInvoiceList(exhibitor_id, page, limit);
    if (result && result.data && result.data.list) {
      invoiceList.value = result.data.list;
      // 更新分页信息
      pagination.value = {
        total: result.data.total,
        page: result.data.page,
        limit: result.data.page_size
      };
    } else {
      console.warn("API返回数据格式不正确:", result);
      invoiceList.value = [];
    }
  } catch (error) {
    console.error("获取发票列表失败:", error);
    invoiceList.value = [];
  } finally {
    loading.value = false;
  }
};

// 分页改变
const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  getInvoiceListData(page, 10);
};

const handleRefresh = () => {
  // 调用列表查询接口
  console.log("刷新");
  getInvoiceListData(pagination.value.page, 10);
};

// 自定义头部组件，无需header配置

const handleAdd = () => {
  console.log("打开申请发票表单");
  formMode.value = "add";
  // 设置默认数据，从store获取exhibitor_id，status 为 3（待提交）
  const exhibitor_id = getExhibitorId();
  currentFormData.value = {
    id: 0,
    exhibitor_id: exhibitor_id || 0,
    bill_type: "",
    bill_project: "",
    amount: "",
    bill_info: "",
    tax_number: "",
    reg_addres: "",
    reg_phone: "",
    bank: "",
    mail_address: "",
    status: 3
  };
  isShowEditDialog.value = true;
};

const handleFormSubmit = async (formData: ApplyInvoiceType) => {
  try {
    console.log("开始提交表单数据:", formData);

    let result: ApplyInvoiceResult;

    if (formMode.value === "edit") {
      // 修改模式
      result = await updateInvoice(formData);
      console.log("修改发票结果:", result);
    } else {
      // 新增模式
      result = await applyInvoice(formData);
      console.log("申请发票结果:", result);
    }

    if (result.code === 0) {
      ElMessage.error(
        formMode.value === "edit"
          ? "发票修改失败！"
          : "发票申请提交失败！" + result.msg
      );
      return;
    } else {
      ElMessage.success(
        formMode.value === "edit" ? "发票修改成功！" : "发票申请提交成功！"
      );
      // 关闭弹窗
      isShowEditDialog.value = false;
      // 刷新列表
      getInvoiceListData(pagination.value.page, 10);
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error(
      formMode.value === "edit"
        ? "发票修改失败，请重试！"
        : "申请发票失败，请重试！"
    );
  }
};
// 查看
const handleView = async (id: number) => {
  try {
    const exhibitor_id = getExhibitorId();
    const result = await getInvoiceDetail(id, exhibitor_id);
    console.log("发票详情:", result.data);

    // 将API数据转换为表单数据格式
    const formData: ApplyInvoiceType = {
      id: result.data.id,
      exhibitor_id: result.data.exhibitor_id,
      bill_type: result.data.bill_type,
      bill_project: result.data.bill_project,
      amount: result.data.amount,
      bill_info: result.data.bill_info,
      tax_number: result.data.tax_number,
      reg_addres: result.data.reg_addres,
      reg_phone: result.data.reg_phone,
      bank: result.data.bank,
      mail_address: result.data.mail_address,
      status: result.data.status
    };

    formMode.value = "view";
    currentFormData.value = formData;
    isShowEditDialog.value = true;
  } catch (error) {
    console.error("获取发票详情失败:", error);
    ElMessage.error("获取发票详情失败！");
  }
};

// 修改
const handleEdit = async (id: number) => {
  try {
    const exhibitor_id = getExhibitorId();
    const result = await getInvoiceDetail(id, exhibitor_id);
    console.log("发票详情:", result.data);

    if (result.data.status === 0) {
      ElMessage.error("发票正在审核中，请稍后再试");
    } else if (result.data.status === 1) {
      ElMessage.error("发票审核已通过，请重新申请");
    } else {
      // 将API数据转换为表单数据格式
      const formData: ApplyInvoiceType = {
        id: result.data.id,
        exhibitor_id: result.data.exhibitor_id,
        bill_type: result.data.bill_type,
        bill_project: result.data.bill_project,
        amount: result.data.amount,
        bill_info: result.data.bill_info,
        tax_number: result.data.tax_number,
        reg_addres: result.data.reg_addres,
        reg_phone: result.data.reg_phone,
        bank: result.data.bank,
        mail_address: result.data.mail_address,
        status: result.data.status
      };

      formMode.value = "edit";
      currentFormData.value = formData;
      isShowEditDialog.value = true;
    }
  } catch (error) {
    console.error("获取发票详情失败:", error);
    ElMessage.error("获取发票详情失败！");
  }
};

// 传递响应式引用，而不是值
const { tableData, columns } = useColumns(
  invoiceList,
  handleEdit,
  handleView,
  handleRefresh
);

const handleCancel = () => {
  isShowEditDialog.value = false;
};

const isShowEditDialog = ref(false);
const formMode = ref<"add" | "view" | "edit">("add"); // 表单模式：新增、查看、修改
const currentFormData = ref<ApplyInvoiceType | null>(null); // 当前表单数据
</script>

<template>
  <div>
    <!-- 统一的白色背景容器 -->
    <div class="table-container">
      <!-- 自定义头部 -->
      <div class="custom-header">
        <div class="header-left">
          <h2 class="header-title">发票信息</h2>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            申请发票
          </el-button>
        </div>
      </div>

      <!-- 表格 -->
      <pure-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :scroll="{ x: 1800 }"
        style="width: 100%"
      />

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          :page-size="10"
          :total="pagination.total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 弹框放在最外层，避免被其他组件影响 -->
    <div v-if="isShowEditDialog" class="myform">
      <InvoiceInfoForm
        :mode="formMode"
        :initial-data="currentFormData"
        @cancel="handleCancel"
        @confirm="handleFormSubmit"
      />
    </div>
  </div>
</template>

<style scoped>
/* 统一的白色背景容器 */
.table-container {
  background-color: #fff;
  padding: 0 20px;
}

/* 自定义头部样式 */
.custom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.header-left .header-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 分页容器样式 */
.pagination-container {
  padding: 20px 0;
  text-align: center;
  display: flex;
  justify-content: center;
  width: 100%;
}

/* 表格滚动条样式 */
:deep(.el-table) {
  overflow-x: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 固定列样式 */
:deep(.el-table__fixed-right) {
  box-shadow: -2px 0 8px rgb(0 0 0 / 10%);
}

:deep(.el-table__fixed) {
  box-shadow: 2px 0 8px rgb(0 0 0 / 10%);
}
</style>
